package com.itany.book.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.constant.StatusConst;
import com.itany.exception.ManagerServiceException;
import com.itany.mapper.BookMapper;
import com.itany.mapper.BookTypeMapper;
import com.itany.mapper.PressMapper;
import com.itany.pojo.*;
import com.itany.service.BookService;
import com.itany.utils.MyHttpClientUtils;
import com.itany.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private PressMapper pressMapper;
    @Autowired
    private BookTypeMapper bookTypeMapper;

    @Override
    public Integer addBook(BookWithBLOBs book, String pressName, String bookType, String bookType2) throws ManagerServiceException {
        String isbn = book.getIsbn();
        if (!StringUtils.isIsbn(isbn)) {
            throw new ManagerServiceException("isbn格式错误");
        }

        BookWithBLOBs bookWithBLOBs = selectBookBy(isbn);
        if (bookWithBLOBs != null) {
            throw new ManagerServiceException("已存在");
        }

        Integer pressId = null;
        Integer bookTypeId = null;
        //添加 bookId
        if (!StringUtils.isEmpty(pressName)) {
            Press press = selectPressBy(pressName);
            if (press != null) {
                pressId = press.getId();
            } else {
                pressId = addPress(pressName);
            }
        }
        // 添加 bookTypeId ,有时
        if (!StringUtils.isEmpty(bookType) && !StringUtils.isEmpty(bookType2)) {
            BookType type2 = selectBookTypeBy(bookType2);
            if (type2 != null) {
                bookTypeId = type2.getId();
            } else {
                //查找父类型
                Integer pid = null;
                BookType type1 = selectBookTypeBy(bookType);
                if (type1 != null) {
                    pid = type1.getId();
                } else {
                    // 没找到 添加父类型
                    BookType type = new BookType();
                    type.setTypetext(bookType);
                    bookTypeMapper.insertSelective(type);
                    pid = type.getId();
                }
                //添加子类型
                BookType type = new BookType();
                type.setTypetext(bookType2);
                type.setPid(pid);
                bookTypeMapper.insertSelective(type);
                bookTypeId = type.getId();
            }
        }

        book.setPressid(pressId);
        book.setTypeid(bookTypeId);

        addBook(book);
        return book.getId();
    }

    @Override
    public Integer addBook(BookWithBLOBs book) throws ManagerServiceException {
        String isbn = book.getIsbn();
        if (!StringUtils.isIsbn(isbn)) {
            throw new ManagerServiceException("isbn格式错误");
        }
        bookMapper.insertSelective(book);

        return book.getId();
    }

    @Transactional(readOnly = true)
    @Override
    public BookWithBLOBs selectBookBy(String isbn) throws ManagerServiceException {
        if (!StringUtils.isIsbn(isbn)) {
            throw new ManagerServiceException("isbn格式错误");
        }
        BookExample example = new BookExample();
        example.or().andIsbnEqualTo(isbn);
        List<BookWithBLOBs> list = bookMapper.selectByExampleWithBLOBs(example);
        return list.isEmpty() ? null : list.get(0);
    }

    @Transactional(readOnly = true)
    @Override
    public Press selectPressBy(String pressName) {
        PressExample example = new PressExample();
        example.or().andNameEqualTo(pressName);
        List<Press> list = pressMapper.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }

    @Transactional(readOnly = true)
    @Override
    public BookType selectBookTypeBy(String bookType) {
        BookTypeExample example = new BookTypeExample();
        example.or().andTypetextEqualTo(bookType);
        List<BookType> list = bookTypeMapper.selectByExample(example);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public Integer addPress(String pressName) throws ManagerServiceException {
        if (StringUtils.isEmpty(pressName)) {
            throw new ManagerServiceException("参数为空");
        }
        Press press = new Press();
        press.setFlag(StatusConst.ENABLE);
        press.setName(pressName);
        pressMapper.insertSelective(press);
        return press.getId();
    }

    @Override
    public Integer addBookType(String bookType, Integer pid) throws ManagerServiceException {
        if (StringUtils.isEmpty(bookType)) {
            throw new ManagerServiceException("参数为空");
        }
        BookType type = new BookType();
        type.setPid(pid);
        type.setTypetext(bookType);
        bookTypeMapper.insertSelective(type);
        return type.getId();
    }

    @Override
    public PageInfo<BookWithBLOBs> selectExample(Integer page, Integer rows, BookWithBLOBs book, Integer supplierid) {
        BookExample example = new BookExample();
        example.or().andIdEqualTo(book.getId());
        PageHelper.startPage(page, rows);
        List<BookWithBLOBs> bookWithBLOBs = bookMapper.selectByExampleWithBLOBs(example);
        PageInfo<BookWithBLOBs> info = new PageInfo<>(bookWithBLOBs);
        return info;
    }

    @Override
    public void update(BookWithBLOBs book) throws ManagerServiceException {
        try {
            bookMapper.updateByPrimaryKeySelective(book);
        } catch (Exception e) {
            throw new ManagerServiceException("修改失败");
        }
    }

    @Transactional(readOnly = true)
    @Override
    public BookWithBLOBs selectById(Integer id) {

        BookWithBLOBs book = bookMapper.selectByPrimaryKey(id);
        return book;
    }

    @Override
    public PageInfo<BookWithBLOBs> supplierFindAll(Integer page, Integer rows, Integer supplierid, String bookname, String isbn) {
        PageHelper.startPage(page,rows);
        List<BookWithBLOBs> list = bookMapper.supplierSelectAll(supplierid, bookname, isbn);
        PageInfo<BookWithBLOBs> info = new PageInfo<>(list);
        return info;
    }

    @Override
    public BookWithBLOBs findIsbn(String isbn) throws ManagerServiceException {
        if (!StringUtils.isIsbn(isbn)) {
            throw new ManagerServiceException("ISBN格式不对");
        }
        //查找本地
        BookExample example = new BookExample();
        example.or().andIsbnEqualTo(isbn);
        List<BookWithBLOBs> books = bookMapper.selectByExampleWithBLOBs(example);

        if (!books.isEmpty()) {
            return books.get(0);
        }

        String get = MyHttpClientUtils.doGet("http://feedback.api.juhe.cn/ISBN?key=303033e62d74312d1a9a72464b485517&sub=" + isbn);
        JSONObject object = JSON.parseObject(get);
        Integer code = object.getInteger("error_code");
        if (code != 0) {
            throw new ManagerServiceException("isbn查询接口异常 :" + get);
        }
        BookWithBLOBs book = new BookWithBLOBs();
        book.setIsbn(isbn);
        JSONObject result = object.getJSONObject("result");

        String author = result.getString("author");
        book.setAuthor(author);
        String bookname = result.getString("title");
        book.setBookname(bookname);
        String pagenumber = result.getString("pages");
        book.setPagenumber(pagenumber);
        String imgurl = result.getString("images_large");
        book.setImgurl(imgurl);
        String bookintroduce = result.getString("summary");
        book.setBookintroduce(bookintroduce);
        String price = result.getString("price");
        book.setPrice(price);
        bookMapper.insertSelective(book);
        return book;
    }

    @Override
    public PageInfo<BookWithBLOBs> selectExample(Integer page, Integer rows, String bookname, String isbn, Integer pressid, Integer supplierid) {
        PageHelper.startPage(page, rows);
        List<BookWithBLOBs> bookWithBLOBs = bookMapper.selectBooksPressSupplier(bookname, isbn, pressid, supplierid);
        PageInfo<BookWithBLOBs> info = new PageInfo<>(bookWithBLOBs);
        return info;
    }
}
